import axios from 'axios'
import config from '../config/index'
import store from '../store/index.js'
import router from '../router/index.js'
import querystring from 'querystring'
import {Loading, Message} from 'element-ui'

var cancelTokenCollection = {}
const instance = axios.create({
  baseURL: config.baseUrl,
  timeout: 1800 * 1000,
  validateStatus: function (status) {
    return status < 500
  },
  // responseType:'blob',
  headers: {
    // 跨域请求 这个配置不能少
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'Accept': 'application/json'
  }
});

let Load = null

// 添加请求拦截器
instance.interceptors.request.use(function (config) {

  // 登录之后接口带上token
  if (store.state.token) {
    config.headers.token = store.state.token
  }
  return config
}, function (error) {
  if (Load) {
    if (Load.visible) {
      Loading.service().close()
      Load = null
    }
  }
  return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 关闭Loading动画
  if (Load) {
    if (Load.visible) {
      Loading.service().close()
      Load = null
    }
  }
  let errorCode = response.data.code
  let msg = response.data.message

  // 相关业务跳转流程
  switch (errorCode) {
    // 无token
    case '400':
      if (Load) {
        if (Load.visible) {
          Loading.service().close();
          Load = null;
        }
      }
      router.push({name: 'login'});
      break;
    // 没有访问权限
    case '402':
      if (Load) {
        if (Load.visible) {
          Loading.service().close();
          Load = null
        }
      }
      router.push({name: 'login'});
      Message.error(msg);
      break;
  }
  return response
}, function (error) {
  // 关闭Loading动画
  if (Load) {
    if (Load.visible) {
      Loading.service().close()
      Load = null
    }
  }
  return Promise.reject(error)
});

// 通过axios发送请求
export default {
  /**
   * @param urlKey 对应API 中的urlkey
   * @param paramObj  发送ajax 传递的参数对象
   * @returns {promise} 返回promise对象
   */
  get: function (urlKey, paramObj) {
    let params = {
      params: paramObj
    };
    return instance.get(urlKey, params);
  },

  /**
   * @param urlKey 对应API 中的urlkey
   * @param paramObj  发送ajax 传递的参数对象
   * @returns {promise} 返回promise对象
   */
  post: function (urlKey, paramObj, configs) {
    // var apiStr = serverPort + api[urlKey];
    // return instance.post(apiStr,paramObj);
    var myConfig = {
      cancelToken: new axios.CancelToken(function (cancel) {
        cancelTokenCollection[urlKey] = cancel;
      })
    };
    //修改Content-Type  参数为querystring.stringify(paramObj)改为paramObj
    if (configs && configs.contentType) {
      myConfig.headers = {
        'Content-Type': configs.contentType
      };
    }else {
      myConfig.headers = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      };
    }
    return instance.post(urlKey, querystring.stringify(paramObj) || paramObj, myConfig);
  },
  updaloadFile: function (urlKey, paramObj) {
    let config = {
      headers:{'Content-Type':'multipart/form-data'}
    };
    return axios.post( urlKey, paramObj, config);
  },
  /**
   * post表单数据 (下载、导出)
   * @param {*} url
   * @param {*} param
   */
  postForm(url, param) {
    let formEl = document.createElement('form');
    formEl.method = 'POST';
    formEl.action = config.baseUrl + url;
    let token = document.createElement('input');
    token.setAttribute('name', 'token');
    token.setAttribute('value', store.state.token);
    formEl.appendChild(token);
    for (let key in param) {
      const val = param[key];
      if (key) {
        let input = document.createElement('input')
        input.name = key;
        input.value = val;
        input.type = 'hidden';
        formEl.appendChild(input);
      }
    }
    document.body.appendChild(formEl);
    formEl.submit();
    document.body.removeChild( formEl );
  },

  /**
   * @param configObj 发送ajax 的配置参数
   * @returns {promise} 返回promise对象
   */
  axios: function (configObj) {
    return axios(configObj)
  },

  all: function () {
    axios.all(arguments).then(axios.spread(function () {
      console.dir(arguments)
    }))
  },

  // 终止 ajax 请求， 如 xhr 的 abort 方法
  cancel: function (urlKey) {
    if (!cancelTokenCollection[urlKey]) {
      return
    }
    cancelTokenCollection[urlKey]()
  }
}
